from itsdangerous import TimedJSONWebSignatureSerializer,BadData
from django.conf import settings
import logging
logger = logging.Logger
def generate_access_token(openid):

    # 对传入的openid 进行加密
    # 600s = 10 min
    serializer = TimedJSONWebSignatureSerializer(settings.SECRET_KEY,expires_in=600)


    # 需要加密的数据
    # data = {'openid':openid}

    # 进行加密 用一个dump()方法
    token = serializer.dumps({'openid': openid})

    # 加密后 解码返回
    return token.decode()


# 对openid 进行解密

def check_access_token(token):
    serializer = TimedJSONWebSignatureSerializer(settings.SECRET_KEY)
    try:
        payload = serializer.loads(token)
    except BadData as e :
        logger.error(e)
        return None

    # 解密后返回的是字典 所以字典取值openid
    return  payload.get('openid')



